<script setup lang="ts">
import { getPreOrderAPI } from '@/services/cart'
import { buyAgainAPI, postMemberOrderAPI } from '@/services/order'
import { useMemberStore } from '@/stores'
import { useAddressStore } from '@/stores/modules/address'
import type { Address } from '@/types/address'
import type { CartItem, PreOrder } from '@/types/cartItem'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { buyNowAPI } from '@/services/goods'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
//获取会员信息
const memberStore = useMemberStore().profile

//定义props，接收父组件传递过来的属性
const query = defineProps<{
  orderId: number
  skuId: number
  goodsCount: number
}>()

//提交订单
const onSubmitOrder = async () => {
  //如果没有收获地址
  if (!selectedAddress.value?.id) {
    return uni.showToast({ title: '请选择收货地址', icon: 'none' })
  }
  //创建订单对象
  const order = {
    userId: memberStore.id,
    addressId: selectedAddress.value?.id,
    orderPrice: totalPrice.value,
    actualPrice: Number(totalPrice.value) + postFee,
    //使用map()将购物车中商品信息转换为订单商品列表
    goods: cartList.value.map((item) => {
      return {
        cartId: item.id,
        skuId: item.skuId,
        goodsId: item.goodsId,
        goodsName: item.name,
        attrsText: item.attrsText,
        quantity: item.count,
      }
    }),
  }
  //发送请求
  const res = await postMemberOrderAPI(order)
  if (res.code === 200) {
    uni.showToast({ title: '下单成功', icon: 'success' })
  } else {
    uni.showToast({ title: '下单失败', icon: 'error' })
  }
  //关闭当前页面
  uni.redirectTo({ url: `/pagesOrder/detail/detail?id=${res.result.id}` })
}

//定义模型
const preOrder = ref<PreOrder>() //预付订单
const cartList = ref<CartItem[]>([]) //购物车列表
const defaultAddress = ref<Address>() //默认地址
const totalPrice = computed(() => {
  //计算商品总价
  return cartList.value.reduce((sum, cart) => {
    return (sum += cart.nowPrice * cart.count)
  }, 0)
})
//获取预付订单详情
const getPreOrder = async () => {
  //当前用户的id
  const userId = memberStore.id
  let res
  //发送请求
  if (query.skuId && query.goodsCount) {
    res = await buyNowAPI(userId, query.skuId, query.goodsCount)
  } else if (query.orderId) {
    res = await buyAgainAPI(userId, query.orderId)
  } else {
    res = await getPreOrderAPI(userId)
  }
  preOrder.value = res.result
  ;({ goods: cartList.value, addressParams: defaultAddress.value } = preOrder.value)
}

//生命周期函数
onLoad(() => {
  //获取预付订单
  getPreOrder()
})
//运费
let postFee = 10.0
//默认地址
const address = useAddressStore()
const selectedAddress = computed(() => {
  if (address.selectedAddress != null) {
    return address.selectedAddress
  }
  return defaultAddress.value
})
</script>
<template>
  <scroll-view scroll-y class="viewport">
    <!-- 收货地址 -->
    <navigator
      v-if="selectedAddress"
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="user"> {{ selectedAddress?.userName }} {{ selectedAddress?.telNumber }}</view>
      <view class="address"
        >{{ selectedAddress?.fullLocation }} {{ selectedAddress?.detail }}
      </view>
      <text class="icon icon-right"></text>
    </navigator>
    <navigator
      v-else
      class="shipment"
      hover-class="none"
      url="/pagesMember/address/address?from=order"
    >
      <view class="address"> 请选择收货地址 </view>
      <text class="icon icon-right"></text>
    </navigator>

    <!-- 商品信息 -->
    <view class="goods">
      <navigator
        v-for="item in cartList"
        :key="item.id"
        :url="`/pages/goods/goods?id=${item.goodsId}`"
        class="item"
        hover-class="none"
      >
        <img class="picture" :src="item.picture" />
        <view class="meta">
          <view class="name ellipsis"> {{ item.name }} </view>
          <view class="attrs">{{ item.attrsText }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.nowPrice }}</view>
            <view class="price symbol">{{ item.price }}</view>
          </view>
          <view class="count">x{{ item.count }}</view>
        </view>
      </navigator>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{ Number(totalPrice).toFixed(2) }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{ postFee }}</text>
      </view>
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay symbol">
      <text class="number">{{ (Number(totalPrice) + postFee).toFixed(2) }}</text>
    </view>
    <view class="button" :class="{ disabled: selectedAddress === null }" @tap="onSubmitOrder">
      提交订单
    </view>
  </view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png)
    20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #3c69dc;
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>
